const Koa = require('koa')
const static = require('koa-static')
const mount = require('koa-mount')
const bodyParser = require('koa-bodyparser')
const dotenv = require('dotenv')

// 加载.env
dotenv.config()

// 加载全局变量
require('./libs/global')

// token auth 中间件
const jwtAuth = require('./libs/jwt')
const app = new Koa()


// 基础中间件
app.use(async (ctx, next) => {
  const start = Date.now()
  await next()
  const ms = Date.now() - start
  var info = `${ctx.method} ${ctx.status} ${ctx.url} - ${ms} ms`
  if (ctx.status > 400 && ctx.status < 500) {
    log.warn(info)
  } else if (ctx.status < 400) {
    log.success(info)
  } else {
    log.info(info)
  }
})

// session相关
// app.keys = ['123456']
// app.use(session({
//   cookie: {secure: false, maxAge:86400000},
//   // store: RedisStore(redisConf.session)
// }, app))

// post解析，不支持文件上传
app.use(bodyParser())


// 初始化tokenAuth
/**
* ctx.state.token
* ctx.state.auth
* ctx.state.tokenErr
* ctx.user
* ctx.auth
* ctx.login
**/
app.use(jwtAuth.initialize())
var router = require('./routes')

app.use(mount('/admin', static('./dist', {maxage: 24 * 60 * 60 * 1000})))
app.use(mount('/static', static('./dist/static', {maxage: 24 * 60 * 60 * 1000})))
app.use(mount('/', static('./public', {maxage: 24 * 60 * 60 * 1000})))

app.use(router.routes())
app.use(router.allowedMethods())

// 404
router.all('404', '*', ctx => {
  ctx.status = 404
  ctx.body = `
    <title>404 - 乐清花会后台管理系统</title>
    <h4 style="color: #20292f;
    font-family: roboto;
    font-weight: 100;">404 Page Not Found !</h4>
    <p style="color: #b2b2b2">乐清花会后台管理系统 &copy; make by <a href="https://www.github.com/mengdu">@lanyue</a></p>
  `
})
app.on('error', (err, ctx) => {
  log.error(`${ctx.method} ${ctx.url}`, 'Error: ')
  console.log(err)
  // ctx.status = 500
  // ctx.body = {name: err.name, message: err.message}
})

app.listen(process.env.PORT)
log('listening on ' + process.env.PORT)

module.exports = app
